終於要把整個資料庫建立起來了,官方文件說建立資料庫的過程很花資源,所以最好使用單例,然後把 Dao 做成抽像類別。
@Database
,目前我們只有一個實體,所以entities = [Note::class]
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class HackNoteDatabase : RoomDatabase() {
abstract val noteDatabaseDao: NoteDatabaseDao
}
@Database(entities = [Note::class, User::class], version = 1, exportSchema = false)
abstract class HackNoteDatabase : RoomDatabase() {
abstract val noteDatabaseDao: NoteDatabaseDao
abstract val userDatabaseDao: UserDatabaseDao
}
version = 1
,以後如果編譯不過就要把版號增加一
@Database(entities = [Note::class], version = 999, exportSchema = false)
abstract class HackNoteDatabase : RoomDatabase() {
abstract val noteDatabaseDao: NoteDatabaseDao
}
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class HackNoteDatabase : RoomDatabase() {
abstract val noteDatabaseDao: NoteDatabaseDao
companion object {
@Volatile
private var INSTANCE: HackNoteDatabase? = null
fun getInstance(context: Context): HackNoteDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
HackNoteDatabase::class.java,
"note_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
}